import { useClipboard } from '@vueuse/core'
import { ElMessage } from 'element-plus'
import { nanoid } from 'nanoid'

/**
 * 复制文本
 */
export async function copyText(value: string) {
  const { copied, copy, isSupported } = useClipboard()

  if (!isSupported) {
    ElMessage.warning('不支持复制到剪贴板')
    return false
  }

  await copy(value)

  return copied.value
}

/**
 * 下载文件
 */
export function downloadFile(res: any, filename = '') {
  const data = res.body
  const name =
    filename ||
    decodeURIComponent(res.headers['content-disposition'].split('=')[1])

  const unit8array = new Uint8Array(data.data)
  const blob = new Blob([unit8array], { type: 'application/octet-stream' })

  const href = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = href
  a.download = name
  a.click()
  URL.revokeObjectURL(a.href)
}

/**
 * 生成随机ID
 */
export function genRandomID(size?: number) {
  return nanoid(size)
}
